'''
<增加>用户 链接以下地址: user/add/
<修改>用户 链接以下地址: user/add/?uid={{ 用户id }} 需要参数uid为用户id
<删除>用户 链接以下地址: user/delete/?uid={{ 用户id }} 需要参数uid为用户id
typeFile -- > python3
coding -- > UTF-8
'''

from django.shortcuts import render, redirect
from models_user.models import *


def user_data(uid):  # 返回渲染菜单选项和默认选择值
    user_obj = User.objects.filter(pk=uid)
    user_dutys, user_duty = user_obj.values_list('duty'), []
    try:
        user_obj = user_obj[0]
    except IndexError:
        raise IndexError('没有该用户')
    if user_dutys[0][0]:
        for i in user_dutys:
            user_duty.append(int(i[0]))
    return user_obj, user_duty


def add_user(request):  # 增加 and 修改 功能
    list_duty = Duty.objects.all().values()
    uid = request.GET.get('uid')
    if request.method == 'GET' and uid:
            user_obj, user_duty = user_data(uid)[0], user_data(uid)[1]
    elif request.method == 'GET':
        mes = '删除成功' if request.GET.get('user_del') else ''
    elif request.method == 'POST':
        name = request.POST['user']
        pswd = request.POST['pswd']
        sex = 1 if request.POST.get('sex') else 2
        dutys = request.POST.getlist('dutys')
        if uid:
            user = User.objects.get(pk=uid)
            user.name = name
            user.pswd = pswd
            user.sex_id = sex
            user.duty.clear()
            user.duty.add(*dutys)
            user.save()
            mes = '修改成功'
            user_obj, user_duty = user_data(uid)[0], user_data(uid)[1]
        else:
            try:
                User.objects.get(name=name, pswd=pswd, sex_id=sex)
            except User.DoesNotExist:
                User.objects.create(name=name, pswd=pswd, sex_id=sex)
            user = User.objects.get(name=name, pswd=pswd, sex_id=sex)
            user.duty.add(*dutys)
            mes = '提交完成!'
    else:
        mes = '数据异常!'
    return render(request, 'add_user/add_user.html', locals())


def delete_user(request):  # 删除功能，跳转至增加页面
    uid = request.GET['uid']
    user_obj = User.objects.get(pk=uid)
    user_obj.duty.clear()
    user_obj.delete()
    return redirect('/user/add/?user_del=删除成功')


